/*
 * Copyright 2022 The Open Islands Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.openislands.oi.util;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;

public class EnumUtils {
    /***
     * returns a subset of all enums for which filterFunction evaluates to true
     * @param clazz          an enum class
     * @param filterFunction filter function
     * @param <E>            an enum
     * @return Set<Enum -> filterFunction is true>
     */
    @SuppressWarnings("unchecked")
    public static <E extends Enum<E>> Set<E> filter(Class<E> clazz, Function<E, Boolean> filterFunction) {
        Set<E> result = new HashSet<>();
        Enum<E>[] enumConstants = clazz.getEnumConstants();
        for (Enum<E> enumConstant : enumConstants) {
            final E anEnum = (E) enumConstant;
            if (filterFunction.apply(anEnum)) {
                result.add(anEnum);
            }
        }
        return result;
    }

    /***
     * get enum constant based on enum field name and value
     * @param clazz     an enum class
     * @param field     enum field
     * @param value     field value
     * @param <E>       an enum
     * @return enum constant
     */
    @SuppressWarnings("unchecked")
    public static <E extends Enum<E>> E byField(Class<E> clazz, String field, Object value) throws ReflectiveOperationException {
        final Field clazzField = clazz.getDeclaredField(field);
        clazzField.setAccessible(true);
        Enum<E>[] enumConstants = clazz.getEnumConstants();
        for (Enum<E> enumConstant : enumConstants) {
            final Object fieldValue = clazzField.get(enumConstant);
            if (fieldValue.equals(value)) {
                return (E) enumConstant;
            }
        }
        return null;
    }
}
